/*************************************
 * Created by WebStorm
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time :2024/10/21 19:37
 Desc :
 **************************************/

import {Config} from '@/config';

interface socket {
    websocket: any
    init: (e: any) => any,
    send: (e: any) => void
}

const socket: socket = {
    websocket: null,
    init: (e: any) => {
        //线上地址:wss://mingdil.c8plus.net/ws  本地地址:ws://127.0.0.1:8007/ws
        const ws_url: string = 'ws://' + Config.WS_URL;
        socket.websocket = new WebSocket(ws_url);
        //初始化时需要传入用户或管理员id
        socket.websocket.onopen = () => {
            socket.websocket.send(JSON.stringify(e))
        };
        //处理数据
        socket.websocket.onmessage = (e: any) => {
            if (e.data == 'ping') {
                socket.send('pong')
            } else {
                const data = JSON.parse(e.data);
                console.log(data)
            }
        };
        //监听WS服务器连接断开状态
        socket.websocket.onclose = (_e: any) => {
            console.log("WS服务器连接断开！")
        }
    },
    //发送消息
    send: (e: any) => {
        socket.websocket.send(JSON.stringify(e))
    }
}
export default socket;